package com.example.demo.ImgTest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.HTTPTest.util.OKHttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

@Slf4j
@Component
public class PatSaveLocally {

    /**
     * 每天凌晨1点执行 0 0 1 * * ?
     * 测试：0 0/2 * * * ?
     */
//    @Scheduled(cron = "0/20 * * * * ?")
    public void getPic() throws Exception {
//    public static void main(String[] args) throws Exception {

        // 先根据预制点位转到指定角度

        // 然后拍照片存至本地
        String url = "https://open.ys7.com/api/lapp/device/capture";
        RequestBody requestBody = new FormBody.Builder()
                .add("accessToken", "at.20c6dyrp449o30u9a4fizmya71gs10tg-2a4mnyoa5t-06ahwcy-y8kx5tlbc")
                .add("deviceSerial", "L21760801")
                .add("channelNo", "1")
                .add("quality", "1")
                .build();
        Map<String, Object> dopost = OKHttpUtil.dopostgetPat(url, requestBody);

        String result = dopost.get("result").toString();
        JSONObject parseObject = JSON.parseObject(result);
        String code = parseObject.getString("code");

        String imgUrl = null;
        if ("200".equals(code)) {
            JSONObject data = parseObject.getJSONObject("data");
            imgUrl = data.getString("picUrl");
        }

        // 下载路径
        String localPath = "D:/upload_files/yanhai";
        // 文件夹名称
        String folderName = "OiOiOi";
        // 图片后缀
        String imgSuffix = ".png";

        // 将图片下载至本地
        Boolean picUrl = download(localPath, folderName, imgUrl, imgSuffix);
        // 图片大小为2650*1440
        System.out.println(picUrl);
    }

    /**
     * 下载图片
     *
     * @param localPath  下载路径
     * @param folderName 文件夹名称
     * @param urlString  图片源地址
     * @param imgSuffix  图片后缀
     * @return Boolean
     */
    public static Boolean download(String localPath, String folderName, String urlString, String imgSuffix) throws Exception {
        // 构造URL
        URL url;
        // 打开连接
        URLConnection con;
        // 输入流
        InputStream is;
        String filename;
        try {
            url = new URL(urlString);
            con = url.openConnection();
            is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;

            // 输出的文件流
            //下载路径及下载图片名称
            File file1 = new File(localPath + "/" + folderName);
            if (!file1.exists()) {
                file1.mkdir();
            }
            filename = localPath + "/" + folderName + "/" + System.currentTimeMillis() + imgSuffix;
            File file = new File(filename);
            FileOutputStream os = new FileOutputStream(file, true);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        log.info(filename);
        return true;
    }
}
